package com.baijiayun.liveuibase.toolbox.answerer;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;

import androidx.annotation.IntDef;
import androidx.core.content.ContextCompat;

import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Switch;
import android.widget.TextView;

import com.baijiayun.livecore.context.LPConstants;
import com.baijiayun.livecore.context.LPConstants.ComponentType;
import com.baijiayun.livecore.models.LPAnswerModel;
import com.baijiayun.livecore.models.LPAnswerRecordModel;
import com.baijiayun.livecore.models.LPAnswerSheetOptionModel;
import com.baijiayun.livecore.models.LPGroupItem;
import com.baijiayun.livecore.models.LPUserAnswerDetail;
import com.baijiayun.livecore.models.LPUserModel;
import com.baijiayun.livecore.utils.LPLogger;
import com.baijiayun.livecore.utils.LPRxUtils;
import com.baijiayun.liveuibase.R;
import com.baijiayun.liveuibase.base.BaseWindow;
import com.baijiayun.liveuibase.base.QueryPlus;
import com.baijiayun.liveuibase.toolbox.answerer.barchart.AnswererBarChart;
import com.baijiayun.liveuibase.utils.DisplayUtils;
import com.baijiayun.liveuibase.utils.ThemeDataUtil;
import com.baijiayun.liveuibase.utils.drawable.DrawableBuilder;
import com.baijiayun.liveuibase.utils.drawable.StateListDrawableBuilder;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * 老师答题器
 * 注释部分是查看记录
 */
public class AdminAnswererWindow extends BaseWindow {
    private QueryPlus a$, aa$, ab$, b$;
    private CompositeDisposable disposables;
    private Disposable timeDisposable;
    private int optionsCount;
    private EditText etRemark;
    private EditText etCountDown;
    private List<Boolean> checkList;
    private List<String> judgementTypes;
    private List<String> activeJudegementTypes;
    private boolean hasSetRightAnswer;
    private boolean isJudgement;
    private boolean isRight, isWrong;
    private boolean isCustomEdit;
    private LPAnswerModel lpAnswerModel;
    private Map<Object, LPAnswerRecordModel> recordMap;
    private RecordAdapter detailAdapter;
    private int currentWindowStatus;
    private boolean isFirstInit;
    private long duration;
    private long endTimeMillis;
    private static final int OPTIONS_COUNT_DEFAULT = 4;
    private static final int OPTIONS_COUNT_MAX = 8;
    private static final int OPTIONS_COUNT_MIN = 2;
    private static final int TIME_MINUTE_MAX = 999;
    private static final int TIME_MINUTE_MIN = 1;
    public static final int STATUS_ANSWER_BEFORE = 0;
    public static final int STATUS_ANSWERING = 1;
    public static final int STATUS_ANSWERED = 2;
    public static final int STATUS_ANSWER_DETAIL = 3;

    @IntDef({STATUS_ANSWER_BEFORE, STATUS_ANSWERING, STATUS_ANSWERED, STATUS_ANSWER_DETAIL})
    @Retention(RetentionPolicy.SOURCE)
    public @interface WindowStatus {
    }

    public AdminAnswererWindow(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public AdminAnswererWindow(Context context, LPAnswerModel lpAnswerModel) {
        super(context);
        this.context = context;
        this.lpAnswerModel = lpAnswerModel;
        init();
    }

    private void init() {
        disposables = new CompositeDisposable();
        isFirstInit = true;
        optionsCount = OPTIONS_COUNT_DEFAULT;
        judgementTypes = new ArrayList<>(Arrays.asList(context.getResources().getStringArray(R.array.base_judgement_type)));
        List<String> list = routerListener.getAnswerCustomerType();
        judgementTypes.addAll(1, list);
        activeJudegementTypes = new ArrayList<>();
        activeJudegementTypes.addAll(judgementTypes);
        LinearLayout llContainer = $.id(R.id.ll_container).view();
        disposables.add($.id(R.id.iv_close).clicks().throttleFirst(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(o -> closeWindow()));
        View questionView = View.inflate(context, R.layout.uibase_answerer_window_question, null);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        llContainer.addView(questionView, STATUS_ANSWER_BEFORE, layoutParams);
        View answeringView = View.inflate(context, R.layout.uibase_answerer_window_answering, null);
        answeringView.findViewById(R.id.tv_end).setSelected(true);
        answeringView.setVisibility(View.GONE);
        llContainer.addView(answeringView, STATUS_ANSWERING, layoutParams);
        View resultView = View.inflate(context, R.layout.uibase_answerer_window_result, null);
        resultView.setVisibility(View.GONE);
        llContainer.addView(resultView, STATUS_ANSWERED, layoutParams);
        View detailView = View.inflate(context, R.layout.uibase_answerer_window_detail, null);
        detailView.setVisibility(View.GONE);
        llContainer.addView(detailView, STATUS_ANSWER_DETAIL, layoutParams);

        initQuestionView(questionView);
        currentWindowStatus = STATUS_ANSWER_BEFORE;
        //老师助教同步状态--开始答题--->> 答题中
        if (lpAnswerModel != null) {
            initAnsweringView(lpAnswerModel);
            changeWindow(STATUS_ANSWERING);
        }
        disposables.add(routerListener.getLiveRoom().getToolBoxVM().getObservableOfAnswerStart()
                .observeOn(AndroidSchedulers.mainThread()).subscribe(lpAnswererModel -> {
                    initAnsweringView(lpAnswererModel);
                    changeWindow(STATUS_ANSWERING);
                }));
        disposables.add(routerListener.getLiveRoom().getToolBoxVM().getObservableOfAnswerEnd()
                .observeOn(AndroidSchedulers.mainThread()).subscribe(lpAnswerEndModel -> {
                    LPRxUtils.dispose(timeDisposable);
                    if (lpAnswerEndModel.isRevoke) {
                        if (currentWindowStatus == STATUS_ANSWERING) {
                            reEdit();
                        }
                    } else {
                        if (currentWindowStatus == STATUS_ANSWERING) {
                            endTimeMillis = lpAnswerEndModel.timeEnd;
                            changeWindow(STATUS_ANSWERED);
                            generateResultView(this.lpAnswerModel);
                        }
                    }
                }));
        disposables.add(routerListener.getLiveRoom().getToolBoxVM().getObservableOfAnswerUpdate()
                .observeOn(AndroidSchedulers.mainThread()).subscribe(lpAnswererModel -> {
                    if (currentWindowStatus == STATUS_ANSWERING) {
                        changeAnsweringView(lpAnswererModel);
                    }
                    if (currentWindowStatus == STATUS_ANSWERED) {
                        generateResultView(lpAnswererModel);
                    }
                }));
        disposables.add(routerListener.getLiveRoom().getToolBoxVM().getObservableOfAnswerPullRes()
                .observeOn(AndroidSchedulers.mainThread()).subscribe(map -> {
                    recordMap = map;
                    if (detailAdapter != null) {
                        detailAdapter.setNewData(getAllDetailDatas());
                    }
                }));
    }

    /**
     * 答题前---老师出题页面
     *
     * @param questionView
     */
    private void initQuestionView(View questionView) {
        a$ = QueryPlus.with(questionView);
        etRemark = a$.id(R.id.et_remark).view();
        etRemark.addTextChangedListener(remarkWatcher);
        etCountDown = a$.id(R.id.et_countdown).view();
        etCountDown.setText(String.valueOf(TIME_MINUTE_MIN));
        a$.id(R.id.iv_sub).enable(false);
        etCountDown.addTextChangedListener(countDownWatcher);
        @SuppressLint("UseSwitchCompatOrMaterialCode")
        Switch sw = a$.id(R.id.sw_show_answer).view();
        a$.id(R.id.tv_options).view().setSelected(true);
        TextView tvShowAnswer = a$.id(R.id.tv_show_answer).view();
        sw.setOnCheckedChangeListener((buttonView, isChecked) -> {
            tvShowAnswer.setSelected(isChecked);
        });
        disposables.add(a$.id(R.id.iv_add).clicks().throttleFirst(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(o -> changeCountDown(true)));
        disposables.add(a$.id(R.id.iv_sub).clicks().throttleFirst(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(o -> changeCountDown(false)));
        disposables.add(a$.id(R.id.tv_publish).clicks().throttleFirst(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(o -> publish()));
        disposables.add(a$.id(R.id.tv_reset).clicks().throttleFirst(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(o -> reset()));
        disposables.add(a$.id(R.id.tv_options).clicks().throttleFirst(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(o -> {
                    chooseQuestionContentView(false);
                }));
        disposables.add(a$.id(R.id.tv_judgement).clicks().throttleFirst(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(o -> {
                    chooseQuestionContentView(true);
                }));
        LinearLayout llOptionsContainer = a$.id(R.id.ll_options_container).view();
        LinearLayout llJudgementContainer = a$.id(R.id.ll_judgement_container).view();
        generateOptionsView(llOptionsContainer);
        generateJudgementView(llJudgementContainer);
    }

    private Drawable getJudgementDrawable(Context context) {
        return new DrawableBuilder()
                .oval()
                .solidColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_live_product_color))
                .build();
    }

    /**
     * 答题中
     *
     * @param lpAnswerModel
     */
    private void initAnsweringView(LPAnswerModel lpAnswerModel) {
        if (lpAnswerModel == null) {
            LPLogger.e("initAnsweringView lpAnswerModel is null");
            return;
        }
        duration = lpAnswerModel.duration;
        this.lpAnswerModel = lpAnswerModel;
        LPRxUtils.dispose(timeDisposable);
        timeDisposable = Observable.interval(1, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(aLong -> {
                    if (duration <= 0) {
                        end();
                    }
                    if (duration > 0) {
                        duration--;
                        b$.id(R.id.tv_endtime_tip).text(context.getString(R.string.base_answerer_endtime_countdown, getTimeString(duration)));
                    }
                });
        LinearLayout llContainer = $.id(R.id.ll_container).view();
        ViewGroup answeringView = (ViewGroup) llContainer.getChildAt(STATUS_ANSWERING);
        b$ = QueryPlus.with(answeringView);
        b$.id(R.id.tv_remark).text(this.lpAnswerModel.getDescription());
        b$.id(R.id.tv_remark).visibility(TextUtils.isEmpty(this.lpAnswerModel.getDescription()) ? View.GONE : View.VISIBLE);
        b$.id(R.id.tv_endtime_tip).text(context.getString(R.string.base_answerer_endtime_countdown, getTimeString(this.lpAnswerModel.duration)));
        b$.id(R.id.tv_submit_count).text(context.getString(R.string.base_answerer_publish_submit_count, this.lpAnswerModel.userParticipateCount, this.lpAnswerModel.userSubmitCount));
        ViewGroup parentView = b$.id(R.id.ll_options_container).view();
        parentView.removeAllViews();
        if (isFirstInit) {
            isFirstInit = false;
            disposables.add(b$.id(R.id.tv_end).clicks().throttleFirst(500, TimeUnit.MILLISECONDS)
                    .observeOn(AndroidSchedulers.mainThread()).subscribe(o -> end()));
            disposables.add(b$.id(R.id.tv_revoke).clicks().throttleFirst(500, TimeUnit.MILLISECONDS)
                    .observeOn(AndroidSchedulers.mainThread()).subscribe(o -> revoke()));
        }
        List<LPAnswerSheetOptionModel> options = lpAnswerModel.options;
        int size = lpAnswerModel.options.size();
        if (lpAnswerModel.isJudgement()) {
            if (lpAnswerModel.options == null || lpAnswerModel.options.size() != 2) {
                LPLogger.e("initAnsweringView options count onError");
                return;
            }
            View contentView = View.inflate(context, R.layout.uibase_answerer_layout_judgement, null);
            QueryPlus qs = QueryPlus.with(contentView);
            qs.id(R.id.ll_judgement_type).gone();
            qs.id(R.id.tv_setting_answer).gone();
            qs.id(R.id.tv_count_right).visible();
            qs.id(R.id.tv_count_wrong).visible();
            if (lpAnswerModel.options.get(0).isRight) qs.id(R.id.iv_check_right).visible();
            if (lpAnswerModel.options.get(1).isRight) qs.id(R.id.iv_check_wrong).visible();
            qs.id(R.id.tv_option_right).text(lpAnswerModel.options.get(0).text);
            qs.id(R.id.tv_option_wrong).text(lpAnswerModel.options.get(1).text);
            qs.id(R.id.tv_count_right).text(context.getString(R.string.base_answerer_count, lpAnswerModel.options.get(0).selectedCount));
            qs.id(R.id.tv_count_wrong).text(context.getString(R.string.base_answerer_count, lpAnswerModel.options.get(1).selectedCount));
            final Drawable drawable = getJudgementDrawable(context);
            qs.id(R.id.iv_option_wrong).view().setBackground(drawable);
            qs.id(R.id.iv_option_right).view().setBackground(drawable);
            parentView.addView(contentView);
        } else {
            LinearLayout newLayout = null;
            for (int i = 0; i < size; i++) {
                LPAnswerSheetOptionModel optionModel = options.get(i);
                View itemView = View.inflate(context, R.layout.uibase_answerer_item_check_option, null);
                TextView tvOption = itemView.findViewById(R.id.tv_option);
                tvOption.setBackground(getOptionStateListDrawable(context));
                ImageView ivCheck = itemView.findViewById(R.id.iv_check);
                TextView tvCount = itemView.findViewById(R.id.tv_count);
                tvCount.setVisibility(View.VISIBLE);
                tvCount.setText(context.getString(R.string.base_answerer_count, optionModel.selectedCount));
                ivCheck.setVisibility(optionModel.isRight ? View.VISIBLE : View.INVISIBLE);
                tvOption.setText(optionModel.text);
                if (i % 4 == 0) {
                    newLayout = new LinearLayout(context);
                    newLayout.setOrientation(LinearLayout.HORIZONTAL);
                    newLayout.setGravity(Gravity.CENTER_HORIZONTAL);
                    LinearLayout.LayoutParams newLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    newLayoutParams.gravity = Gravity.CENTER_HORIZONTAL;
                    parentView.addView(newLayout, newLayoutParams);
                }
                LinearLayout.LayoutParams itemLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                itemLayoutParams.leftMargin = DisplayUtils.dip2px(context, 8);
                itemLayoutParams.rightMargin = DisplayUtils.dip2px(context, 8);
                itemLayoutParams.topMargin = DisplayUtils.dip2px(context, 4);
                newLayout.addView(itemView, itemLayoutParams);
            }
        }
    }

    private void changeAnsweringView(LPAnswerModel lpAnswerModel) {
        this.lpAnswerModel = lpAnswerModel;
        b$.id(R.id.tv_submit_count).text(context.getString(R.string.base_answerer_publish_submit_count, lpAnswerModel.userParticipateCount, lpAnswerModel.userSubmitCount));
        ViewGroup parentView = b$.id(R.id.ll_options_container).view();
        if (this.lpAnswerModel.isJudgement()) {
            if (parentView.getChildCount() != 1) {
                LPLogger.w("changeAnsweringView parentView childCount onError");
                return;
            }
            View child = parentView.getChildAt(0);
            QueryPlus qs = QueryPlus.with(child);
            qs.id(R.id.tv_count_right).text(context.getString(R.string.base_answerer_count, lpAnswerModel.options.get(0).selectedCount));
            qs.id(R.id.tv_count_wrong).text(context.getString(R.string.base_answerer_count, lpAnswerModel.options.get(1).selectedCount));
        } else {
            if (parentView.getChildCount() <= 0) {
                LPLogger.w("changeAnsweringView parentView childCount onError");
                return;
            }
            List<LPAnswerSheetOptionModel> options = lpAnswerModel.options;
            int childCount = parentView.getChildCount();
            if (childCount > 2) {
                LPLogger.w("changeAnsweringView parentView childCount onError");
                return;
            }
            ViewGroup viewGroup = (ViewGroup) parentView.getChildAt(0);
            for (int i = 0; i < viewGroup.getChildCount(); i++) {
                View child = viewGroup.getChildAt(i);
                TextView textView = child.findViewById(R.id.tv_count);
                textView.setText(context.getString(R.string.base_answerer_count, options.get(i).selectedCount));
            }
            if (childCount == 2) {
                ViewGroup viewGroup1 = (ViewGroup) parentView.getChildAt(1);
                for (int i = 0; i < viewGroup1.getChildCount(); i++) {
                    View child = viewGroup1.getChildAt(i);
                    TextView textView = child.findViewById(R.id.tv_count);
                    textView.setText(context.getString(R.string.base_answerer_count, options.get(viewGroup.getChildCount() + i).selectedCount));
                }
            }
        }
    }

    /**
     * 撤销
     */
    private void revoke() {
        routerListener.getLiveRoom().getToolBoxVM().requestAnswerEnd(true, 0);
    }

    /**
     * 结束
     */
    private void end() {
        LPRxUtils.dispose(timeDisposable);
        routerListener.getLiveRoom().getToolBoxVM().requestAnswerEnd(false, 0);
    }

    /**
     * 答题结束 暂用update的数据
     */
    private void generateResultView(LPAnswerModel lpAnswerModel) {
        this.lpAnswerModel = lpAnswerModel;
        LinearLayout llContainer = $.id(R.id.ll_container).view();
        View resultView = llContainer.getChildAt(STATUS_ANSWERED);
        QueryPlus r$ = QueryPlus.with(resultView);
        AnswererBarChart barChart = r$.id(R.id.barChart).view();
        r$.id(R.id.tv_remark).visibility(TextUtils.isEmpty(this.lpAnswerModel.getDescription()) ? View.GONE : View.VISIBLE);
        r$.id(R.id.tv_remark).text(this.lpAnswerModel.getDescription());
        r$.id(R.id.tv_use_time).text(getTimeStringAppend(endTimeMillis - this.lpAnswerModel.timeStart, context.getString(R.string.base_answer_record_use_time)));
        r$.id(R.id.tv_publish_count).text(context.getString(R.string.base_answerer_publish_count,
                this.lpAnswerModel.userParticipateCount));
        r$.id(R.id.tv_detail).clicked(v -> {
            generateDetailView();
            changeWindow(STATUS_ANSWER_DETAIL);
            detailAdapter.notifyDataSetChanged();
        });
        r$.id(R.id.tv_reedit).clicked(v -> reEdit());
        List<LPAnswerSheetOptionModel> options = this.lpAnswerModel.options;
        int size = options.size();
        String[] axis = new String[size];
        float[] dataList = new float[size];
        List<String> selectedList = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            LPAnswerSheetOptionModel optionModel = options.get(i);
            axis[i] = optionModel.text;
            if (this.lpAnswerModel.userSubmitCount == 0) {
                dataList[i] = 0;
            } else {
                dataList[i] = optionModel.selectedCount * 100.0f / this.lpAnswerModel.userSubmitCount;
            }
            if (optionModel.isRight) {
                selectedList.add(optionModel.text);
            }
        }
        int rateCount = 0;
        if (this.lpAnswerModel.userSubmitCount != 0) {
            rateCount = lpAnswerModel.userCorrectCount * 100 / lpAnswerModel.userSubmitCount;
        }
        barChart.setHorizontalAxis(axis);
        barChart.setDataList(dataList);
        barChart.setSelectedAxis(selectedList);
        barChart.setCountString(context.getString(R.string.base_answerer_submit_count, lpAnswerModel.userSubmitCount));
        barChart.setRateString(context.getString(R.string.base_answerer_right_rate, rateCount));
        r$.id(R.id.barChart).visible();
        barChart.requestLayout();
        barChart.invalidate();
    }

    /**
     * 查看详情
     */
    private void generateDetailView() {
        routerListener.getLiveRoom().getToolBoxVM().requestAnswerPullReq(this.lpAnswerModel.id);
        LinearLayout llContainer = $.id(R.id.ll_container).view();
        View resultView = llContainer.getChildAt(STATUS_ANSWER_DETAIL);
        QueryPlus r$ = QueryPlus.with(resultView);
        r$.id(R.id.tv_reedit).clicked(v -> reEdit());
        r$.id(R.id.tv_return).clicked(v -> changeWindow(STATUS_ANSWERED));
        r$.id(R.id.tv_right_answer).text(context.getString(R.string.base_answerer_right, getRightAnswer()));
        ListView listView = r$.id(R.id.listView).view();
        listView.setDivider(new ColorDrawable(ContextCompat.getColor(context, R.color.base_divider_line_other)));
        listView.setDividerHeight(2);
        detailAdapter = new RecordAdapter(context, getAllDetailDatas());
        listView.setAdapter(detailAdapter);
    }

    private String getRightAnswer() {
        StringBuilder sb = new StringBuilder();
        int size = this.lpAnswerModel.options.size();
        for (int i = 0; i < size; i++) {
            LPAnswerSheetOptionModel optionModel = this.lpAnswerModel.options.get(i);
            if (optionModel.isRight) {
                sb.append(optionModel.text).append(" ");
            }
        }
        return sb.toString();
    }

    private List<LPUserAnswerDetail> getDetailDatas() {
        List<LPUserAnswerDetail> userAnswerDetails = new LinkedList<>();
        if (recordMap != null) {
            LPAnswerRecordModel lpAnswerRecordModel = recordMap.get(this.lpAnswerModel.id);
            if (lpAnswerRecordModel != null) {
                Map<Object, LPUserAnswerDetail> detailMap = lpAnswerRecordModel.userDetails;
                if (detailMap != null) {
                    for (Map.Entry<Object, LPUserAnswerDetail> key : detailMap.entrySet()) {
                        userAnswerDetails.add(replaceUser(key.getValue()));
                    }
                }
            }
        }
        return userAnswerDetails;
    }

    private LPUserAnswerDetail replaceUser(LPUserAnswerDetail lpUserAnswerDetail) {
        for (LPUserModel userModel : getStudentList()) {
            if (userModel.number.equals(lpUserAnswerDetail.user.number)) {
                lpUserAnswerDetail.user.groupId = userModel.groupId;
                lpUserAnswerDetail.user.groupItem = userModel.groupItem;
                return lpUserAnswerDetail;
            }
        }
        return lpUserAnswerDetail;
    }

    private List<LPUserAnswerDetail> getAllDetailDatas() {
        List<LPUserAnswerDetail> detailList = new ArrayList<>();
        List<LPUserAnswerDetail> lpUserAnswerDetailList = getDetailDatas();
        Set<LPUserModel> studentList = getStudentList();
        if (lpUserAnswerDetailList.isEmpty()) {
            for (LPUserModel lpUserModel : studentList) {
                LPUserAnswerDetail answerDetail = new LPUserAnswerDetail();
                answerDetail.user = lpUserModel;
                detailList.add(answerDetail);
            }
        } else {
            if (studentList.size() == lpUserAnswerDetailList.size()) {
                detailList.addAll(lpUserAnswerDetailList);
            } else {
                for (LPUserModel lpUserModel : studentList) {
                    LPUserAnswerDetail answerDetail = new LPUserAnswerDetail();
                    answerDetail.user = lpUserModel;
                    detailList.add(answerDetail);
                }
                for (LPUserAnswerDetail lpUserModel : detailList) {
                    for (LPUserAnswerDetail lpUserAnswerDetail : lpUserAnswerDetailList) {
                        if (lpUserModel.user.userId.equals(lpUserAnswerDetail.user.userId)) {
                            lpUserModel.copy(lpUserAnswerDetail);
                        }
                    }
                }
            }
        }
        return detailList;
    }

    private Set<LPUserModel> getStudentList() {
        final Set<LPUserModel> studentList = new HashSet<>();
        final List<LPGroupItem> groupList = routerListener.getLiveRoom().getOnlineUserVM().getGroupList();
        for (LPGroupItem groupItem : groupList) {
            final List<LPUserModel> userModelList = groupItem.userModelList;
            for (LPUserModel lpUserModel : userModelList) {
                if (lpUserModel.getType() != LPConstants.LPUserType.Teacher && lpUserModel.getType() != LPConstants.LPUserType.Assistant) {
                    lpUserModel.groupItem = groupItem.groupItemModel;
                    studentList.add(lpUserModel);
                }
            }
        }
        if (studentList.isEmpty()) {
            final Set<LPUserModel> userModels = routerListener.getLiveRoom().getOnlineUserVM().getStudentList();
            if (userModels != null && !userModels.isEmpty()) {
                studentList.addAll(userModels);
            }
        }
        return studentList;
    }

    /**
     * 选择题布局
     *
     * @param linearLayout 容器
     */
    private void generateOptionsView(LinearLayout linearLayout) {
        ViewGroup llOptionsContainer = (ViewGroup) View.inflate(context, R.layout.uibase_answerer_layout_options, null);
        aa$ = QueryPlus.with(llOptionsContainer);
        aa$.id(R.id.tv_setting_answer).text(getString(R.string.base_timer_setting_answer));
        LinearLayout llContainer = aa$.id(R.id.ll_options_container).view();
        disposables.add(aa$.id(R.id.iv_add).clicks().throttleFirst(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(o -> changeItemView(llContainer, true)));
        disposables.add(aa$.id(R.id.iv_sub).clicks().throttleFirst(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(o -> changeItemView(llContainer, false)));
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
        linearLayout.addView(llOptionsContainer, layoutParams);
        initItemView(llContainer);
    }

    /**
     * 初始化选择题选项
     *
     * @param linearLayout
     */
    private void initItemView(LinearLayout linearLayout) {
        LinearLayout newLayout = null;
        char start = 'A';
        checkList = new ArrayList<>();
        for (int i = 0; i < OPTIONS_COUNT_MAX; i++) {
            View itemView = View.inflate(context, R.layout.uibase_answerer_item_check_option, null);
            QueryPlus item$ = QueryPlus.with(itemView);
            item$.id(R.id.tv_option).text(String.valueOf(start));
            item$.id(R.id.tv_option).view().setBackground(getOptionStateListDrawable(context));
            ImageView iv = item$.id(R.id.iv_check).view();
            clickListener = new ClickListener(i, iv);
            item$.id(R.id.tv_option).clicked(clickListener);
            item$.id(R.id.iv_check).clicked(clickListener);
            checkList.add(i, false);
            start += 0x01;
            if (i % OPTIONS_COUNT_DEFAULT == 0) {
                newLayout = new LinearLayout(context);
                newLayout.setOrientation(LinearLayout.HORIZONTAL);
                newLayout.setGravity(Gravity.CENTER_HORIZONTAL);
                LinearLayout.LayoutParams containerParmas = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                containerParmas.gravity = Gravity.CENTER_HORIZONTAL;
                linearLayout.addView(newLayout, containerParmas);
            }
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.leftMargin = DisplayUtils.dip2px(context, 8);
            layoutParams.rightMargin = DisplayUtils.dip2px(context, 8);
            layoutParams.topMargin = DisplayUtils.dip2px(context, 2);
            layoutParams.bottomMargin = DisplayUtils.dip2px(context, 2);
            newLayout.addView(itemView, layoutParams);
        }
        linearLayout.getChildAt(1).setVisibility(View.GONE);
    }

    /**
     * 选项增加或者减少
     *
     * @param linearLayout
     * @param isAdd
     */
    private void changeItemView(LinearLayout linearLayout, boolean isAdd) {
        if (isAdd) {
            optionsCount++;
        } else {
            checkList.set(optionsCount - 1, false);
            checkOptionsSettingAnswer();
            optionsCount--;
        }
        aa$.id(R.id.iv_add).enable(optionsCount != OPTIONS_COUNT_MAX);
        aa$.id(R.id.iv_sub).enable(optionsCount != OPTIONS_COUNT_MIN);
        if (optionsCount > OPTIONS_COUNT_DEFAULT) {
            linearLayout.getChildAt(1).setVisibility(View.VISIBLE);
        } else {
            LinearLayout bottomLayout = (LinearLayout) linearLayout.getChildAt(1);
            bottomLayout.setVisibility(View.GONE);
            for (int i = 0; i < bottomLayout.getChildCount(); i++) {
                bottomLayout.getChildAt(i).findViewById(R.id.iv_check).setVisibility(View.INVISIBLE);
            }
        }
        int index = optionsCount > OPTIONS_COUNT_DEFAULT ? 1 : 0;
        int markIndex = optionsCount > OPTIONS_COUNT_DEFAULT ? optionsCount - OPTIONS_COUNT_DEFAULT : optionsCount;
        LinearLayout llContainer = (LinearLayout) linearLayout.getChildAt(index);
        int childCount = llContainer.getChildCount();
        if (childCount != OPTIONS_COUNT_DEFAULT) {
            return;
        }
        for (int i = 0; i < markIndex; i++) {
            llContainer.getChildAt(i).setVisibility(View.VISIBLE);
        }
        for (int i = markIndex; i < OPTIONS_COUNT_DEFAULT; i++) {
            llContainer.getChildAt(i).setVisibility(View.GONE);
            llContainer.getChildAt(i).findViewById(R.id.iv_check).setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 判断题布局
     *
     * @param linearLayout
     */
    private void generateJudgementView(LinearLayout linearLayout) {
        View contentView = View.inflate(context, R.layout.uibase_answerer_layout_judgement, null);
        ab$ = QueryPlus.with(contentView);
        ab$.id(R.id.tv_judgement_type).text(activeJudegementTypes.remove(0));
        CharSequence newString = getJudgementSettingAnswer();
        ab$.id(R.id.tv_setting_answer).text(newString);
        final Drawable drawable = getJudgementDrawable(context);
        ab$.id(R.id.iv_option_right).view().setBackground(drawable);
        ab$.id(R.id.iv_option_wrong).view().setBackground(drawable);
        EditText etOptionRight = ab$.id(R.id.et_option_right).view();
        EditText etOptionWrong = ab$.id(R.id.et_option_wrong).view();
        etOptionRight.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                if (!TextUtils.isEmpty(etOptionWrong.getText()) && TextUtils.isEmpty(etOptionRight.getText())) {
                    showToastMessage(getString(R.string.base_answerer_setting_edit_tip));
                    return;
                }
                if (isCustomEdit && !TextUtils.isEmpty(etOptionRight.getText()) && !TextUtils.isEmpty(etOptionWrong.getText())) {
                    setCustomJudgementType(etOptionRight, etOptionWrong);
                }
            }
        });
        etOptionWrong.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                if (!TextUtils.isEmpty(etOptionRight.getText()) && TextUtils.isEmpty(etOptionWrong.getText())) {
                    showToastMessage(getString(R.string.base_answerer_setting_edit_tip));
                    return;
                }
                if (!TextUtils.isEmpty(etOptionRight.getText()) && !TextUtils.isEmpty(etOptionWrong.getText())) {
                    setCustomJudgementType(etOptionRight, etOptionWrong);
                }
            }
        });
        disposables.add(ab$.id(R.id.ll_judgement_type).clicks().throttleFirst(200, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(o -> showJudgementMenu()));
        TextView tvPublish = a$.id(R.id.tv_publish).view();
        tvPublish.setSelected(true);
        disposables.add(ab$.id(R.id.iv_option_right).clicks().throttleFirst(200, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(o -> {
                    isRight = !isRight;
                    isWrong = false;
                    ab$.id(R.id.iv_check_right).visibility(isRight ? View.VISIBLE : View.INVISIBLE);
                    ab$.id(R.id.iv_check_wrong).invisible();
                    CharSequence rightString = getJudgementSettingAnswer();
                    ab$.id(R.id.tv_setting_answer).text(rightString);
                }));
        disposables.add(ab$.id(R.id.iv_option_wrong).clicks().throttleFirst(200, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(o -> {
                    isWrong = !isWrong;
                    isRight = false;
                    ab$.id(R.id.iv_check_wrong).visibility(isWrong ? View.VISIBLE : View.INVISIBLE);
                    ab$.id(R.id.iv_check_right).invisible();
                    CharSequence wrongString = getJudgementSettingAnswer();
                    ab$.id(R.id.tv_setting_answer).text(wrongString);
                }));
        linearLayout.addView(contentView);
    }

    /**
     * 自定义判断题选项
     *
     * @param etOptionRight
     * @param etOptionWrong
     */
    private void setCustomJudgementType(EditText etOptionRight, EditText etOptionWrong) {
        if (etOptionRight.getText().toString().equals(etOptionWrong.getText().toString())) {
            showToastMessage("两个选项不能相同");
            return;
        }
        ab$.id(R.id.tv_option_right).text(etOptionRight.getText());
        ab$.id(R.id.tv_option_wrong).text(etOptionWrong.getText());
        ab$.id(R.id.tv_option_right).visible();
        ab$.id(R.id.tv_option_wrong).visible();
        ab$.id(R.id.et_option_right).invisible();
        ab$.id(R.id.et_option_wrong).invisible();
        String text = etOptionRight.getText().toString().trim().concat("/").concat(etOptionWrong.getText().toString().trim());
        ab$.id(R.id.tv_judgement_type).text(text);
        CharSequence newString = getJudgementSettingAnswer();
        ab$.id(R.id.tv_setting_answer).text(newString);
        int size = judgementTypes.size();
        if (size == 5) {
            judgementTypes.remove(1);
            judgementTypes.add(judgementTypes.size() - 1, text);
            activeJudegementTypes.remove(1);
        } else {
            judgementTypes.add(size - 1, text);
        }
        routerListener.setAnswerCustomerType(getAddTypes());
        etOptionRight.setText("");
        etOptionWrong.setText("");
        isCustomEdit = false;
    }

    private List<String> getAddTypes() {
        List<String> temp = new ArrayList<>(judgementTypes);
        if (temp.size() > 2) {
            temp.remove(0);
            temp.remove(temp.size() - 1);
        }
        return temp;
    }

    public static void hideInput(Context context, View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    private void showJudgementMenu() {
        hideInput(context, view);
        ab$.id(R.id.iv_judgement_type).view().animate().rotation(180);
        PopupWindow popupWindow = new PopupWindow(context);
        popupWindow.setFocusable(true);
        popupWindow.setWidth(ab$.id(R.id.ll_judgement_type).view().getWidth());
        popupWindow.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.base_common_stronger_layer_bg_with_stroke));
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(context, R.layout.uibase_item_judgement_menu, activeJudegementTypes);
        ListView listView = new ListView(context);
        listView.setDividerHeight(0);
        listView.setAdapter(arrayAdapter);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            if (position == activeJudegementTypes.size() - 1) {
                ab$.id(R.id.tv_option_right).invisible();
                ab$.id(R.id.tv_option_wrong).invisible();
                ab$.id(R.id.et_option_right).visible();
                ab$.id(R.id.et_option_wrong).visible();
                isCustomEdit = true;
                ab$.id(R.id.tv_judgement_type).text(activeJudegementTypes.get(position));
                activeJudegementTypes.clear();
                activeJudegementTypes.addAll(judgementTypes);
            } else {
                String text = activeJudegementTypes.get(position);
                ab$.id(R.id.tv_judgement_type).text(text);
                String[] strs = new String[2];
                try {
                    strs = text.split("/");
                } catch (Exception e) {
                    e.printStackTrace();
                    strs[0] = "";
                    strs[1] = "";
                }
                ab$.id(R.id.tv_option_right).text(strs[0]);
                ab$.id(R.id.tv_option_wrong).text(strs[1]);
                CharSequence newString = getJudgementSettingAnswer();
                ab$.id(R.id.tv_setting_answer).text(newString);
                activeJudegementTypes.clear();
                activeJudegementTypes.addAll(judgementTypes);
                activeJudegementTypes.remove(text);
                if (isCustomEdit) {
                    ab$.id(R.id.tv_option_right).visible();
                    ab$.id(R.id.tv_option_wrong).visible();
                    ab$.id(R.id.et_option_right).invisible();
                    ab$.id(R.id.et_option_wrong).invisible();
                    isCustomEdit = false;
                }
            }
            popupWindow.dismiss();
        });
        popupWindow.setContentView(listView);
        popupWindow.setOnDismissListener(() -> {
            ab$.id(R.id.iv_judgement_type).view().animate().rotation(0);
        });
        popupWindow.showAsDropDown(ab$.id(R.id.ll_judgement_type).view());
    }

    private CharSequence getJudgementSettingAnswer() {
        if (!isRight && !isWrong) {
            return getString(R.string.base_timer_setting_answer);
        }
        String settedAnswer = "";
        try {
            TextView textView = ab$.id(R.id.tv_judgement_type).view();
            String[] strs = textView.getText().toString().trim().split("/");
            settedAnswer = isRight ? strs[0] : strs[1];
        } catch (Exception e) {
            e.printStackTrace();
        }
        String text = context.getString(R.string.base_timer_setted_answer, settedAnswer);
        SpannableStringBuilder builder = new SpannableStringBuilder(text);
        ForegroundColorSpan whiteSpan = new ForegroundColorSpan(ThemeDataUtil.getColorFromThemeConfigByAttrId(
                context, R.attr.base_theme_window_assistant_text_color));
        int index = text.indexOf("：");
        if (index != -1) {
            builder.setSpan(whiteSpan, index + 1, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return builder;
    }

    private void changeCountDown(boolean isAdd) {
        int count = 0;
        String text = etCountDown.getText().toString();
        try {
            count = Integer.parseInt(text);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            count = TIME_MINUTE_MIN;
        }
        count = isAdd ? count + 1 : count - 1;
        if (count <= TIME_MINUTE_MIN) {
            count = TIME_MINUTE_MIN;
        }
        a$.id(R.id.iv_add).enable(count != TIME_MINUTE_MAX);
        a$.id(R.id.iv_sub).enable(count != TIME_MINUTE_MIN);
        etCountDown.setText(String.valueOf(count));
    }

    /**
     * 发布-->答题中页面
     */
    private void publish() {
        if (!hasSetRightAnswer && !isJudgement) {
            showToastMessage(getString(R.string.base_timer_setting_answer));
            return;
        }
        if (isJudgement && !isWrong && !isRight) {
            // do nothing
        }
        if (isJudgement && isCustomEdit) {
            showToastMessage(getString(R.string.base_answerer_setting_edit_tip));
            return;
        }
        LPAnswerModel lpAnswerModel = new LPAnswerModel();
        lpAnswerModel.setType(isJudgement);
        try {
            lpAnswerModel.duration = Integer.parseInt(etCountDown.getText().toString()) * 60;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            lpAnswerModel.duration = 60;
        }
        lpAnswerModel.setDescription(etRemark.getText().toString().trim().replace("\n", " "));
        lpAnswerModel.timeStart = System.currentTimeMillis();
        if (isJudgement) {
            lpAnswerModel.options = getJudgementOptionList();
        } else {
            lpAnswerModel.options = getSheetOptionList();
        }
        @SuppressLint("UseSwitchCompatOrMaterialCode")
        Switch sw = a$.id(R.id.sw_show_answer).view();
        lpAnswerModel.isShowAnswer = sw.isChecked();
        routerListener.getLiveRoom().getToolBoxVM().requestAnswerStart(lpAnswerModel);
    }


    private List<LPAnswerSheetOptionModel> getSheetOptionList() {
        List<LPAnswerSheetOptionModel> lpAnswerSheetOptionModels = new ArrayList<>();
        for (int i = 0; i < optionsCount; i++) {
            LPAnswerSheetOptionModel lpAnswerSheetOptionModel = new LPAnswerSheetOptionModel();
            lpAnswerSheetOptionModel.isRight = checkList.get(i);
            lpAnswerSheetOptionModel.isCorrect = lpAnswerSheetOptionModel.isRight;
            lpAnswerSheetOptionModel.text = String.valueOf((char) ('A' + i));
            lpAnswerSheetOptionModels.add(lpAnswerSheetOptionModel);
        }
        return lpAnswerSheetOptionModels;
    }


    private Drawable getOptionStateListDrawable(Context context) {
        final Drawable drawable = new DrawableBuilder().
                oval()
                .solidColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_live_product_color))
                .build();
        final Drawable selectedDrawable = new DrawableBuilder().
                oval()
                .solidColor(ContextCompat.getColor(context, R.color.base_toolbar_red))
                .build();
        return new StateListDrawableBuilder()
                .normal(drawable)
                .selected(selectedDrawable)
                .build();
    }

    private List<LPAnswerSheetOptionModel> getJudgementOptionList() {
        List<LPAnswerSheetOptionModel> lpAnswerSheetOptionModels = new ArrayList<>();
        LPAnswerSheetOptionModel rightOptionModel = new LPAnswerSheetOptionModel();
        LPAnswerSheetOptionModel wrongOptionModel = new LPAnswerSheetOptionModel();
        TextView tvOptionRight = ab$.id(R.id.tv_option_right).view();
        TextView tvOptionWrong = ab$.id(R.id.tv_option_wrong).view();
        rightOptionModel.text = tvOptionRight.getText().toString().trim();
        rightOptionModel.isRight = isRight;
        rightOptionModel.isCorrect = isRight;
        wrongOptionModel.text = tvOptionWrong.getText().toString().trim();
        wrongOptionModel.isRight = isWrong;
        wrongOptionModel.isCorrect = isWrong;
        lpAnswerSheetOptionModels.add(rightOptionModel);
        lpAnswerSheetOptionModels.add(wrongOptionModel);
        return lpAnswerSheetOptionModels;
    }

    private void reEdit() {
        changeWindow(STATUS_ANSWER_BEFORE);
        reset();
    }

    private void reset() {
        LinearLayout llContainer = aa$.id(R.id.ll_options_container).view();
        llContainer.removeAllViews();
        initItemView(llContainer);
        optionsCount = OPTIONS_COUNT_DEFAULT;
        aa$.id(R.id.iv_add).enable(true);
        aa$.id(R.id.iv_sub).enable(true);
        aa$.id(R.id.tv_setting_answer).text(getString(R.string.base_timer_setting_answer));

        isRight = false;
        isWrong = false;
        ab$.id(R.id.iv_check_right).invisible();
        ab$.id(R.id.iv_check_wrong).invisible();
        CharSequence newString = getJudgementSettingAnswer();
        ab$.id(R.id.tv_setting_answer).text(newString);

        etRemark.setText("");
        etCountDown.setText(String.valueOf(1));

        TextView tvPublish = a$.id(R.id.tv_publish).view();
        if (!isJudgement) {
            tvPublish.setSelected(false);
        }
        hasSetRightAnswer = false;
    }

    private void chooseQuestionContentView(boolean isJudgement) {
        if (this.isJudgement == isJudgement) {
            return;
        }
        a$.id(R.id.ll_options_container).visibility(isJudgement ? View.GONE : View.VISIBLE);
        a$.id(R.id.ll_judgement_container).visibility(isJudgement ? View.VISIBLE : View.GONE);
        this.isJudgement = isJudgement;
        TextView tvJudgement = a$.id(R.id.tv_judgement).view();
        tvJudgement.setSelected(isJudgement);
        TextView tvOptions = a$.id(R.id.tv_options).view();
        tvOptions.setSelected(!isJudgement);
        TextView tvPublish = a$.id(R.id.tv_publish).view();
        if (isJudgement) {
            tvOptions.setTextColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_dialog_negative_text_color));
            tvPublish.setSelected(true);
        } else {
            tvOptions.setTextColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_dialog_positive_text_color));
            tvPublish.setSelected(hasSetRightAnswer);
        }
    }

    /**
     * 切换页面
     */
    private void changeWindow(@WindowStatus int windowStatus) {
        if (windowStatus > STATUS_ANSWER_DETAIL || windowStatus < STATUS_ANSWER_BEFORE) {
            LPLogger.w("status onError");
            return;
        }
        if (windowStatus == currentWindowStatus) {
            LPLogger.w("currentWindowStatus is in effect");
            return;
        }
        LinearLayout llContainer = $.id(R.id.ll_container).view();
        int childCount = llContainer.getChildCount();
        if (windowStatus >= childCount) {
            LPLogger.w("status onError");
            return;
        }
        llContainer.getChildAt(currentWindowStatus).setVisibility(View.GONE);
        llContainer.getChildAt(windowStatus).setVisibility(View.VISIBLE);
        currentWindowStatus = windowStatus;
        if (windowStatus == STATUS_ANSWER_BEFORE) {
            reset();
        }
    }

    private void closeSelf() {
        routerListener.onDismissAnswerer();
    }

    private void closeWindow() {
        LPRxUtils.dispose(timeDisposable);
        routerListener.getLiveRoom().getToolBoxVM().requestAnswerEnd(false, 0);
        routerListener.getLiveRoom().getToolBoxVM().requestComponentDestroy(ComponentType.Answerer);
        closeSelf();
    }

    private String getTimeString(long seconds) {
        return getTimeStringAppend(seconds, "");
    }

    private String getTimeStringAppend(long seconds, String append) {
        StringBuilder sb = new StringBuilder();
        long min = seconds / 60;
        long second = seconds % 60;
        if (seconds != 0) {
            sb.append(append);
            sb.append(min).append(min > 9 ? ":" : "0:")
                    .append(second > 9 ? "" : "0").append(second);
        }
        return sb.toString();
    }

    private TextWatcher remarkWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // don nothing
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            a$.id(R.id.tv_remark_count).text(String.valueOf(s.length()).concat("/50"));
        }

        @Override
        public void afterTextChanged(Editable s) {
            // do nothing
        }
    };
    private TextWatcher countDownWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // do nothing
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (TextUtils.isEmpty(s)) {
                etCountDown.setText(String.valueOf(TIME_MINUTE_MIN));
            }
            try {
                int countdown = Integer.parseInt(s.toString().trim());
                if (countdown < TIME_MINUTE_MIN) {
                    etCountDown.setText(String.valueOf(TIME_MINUTE_MIN));
                }
                a$.id(R.id.iv_sub).enable(countdown != TIME_MINUTE_MIN);
                a$.id(R.id.iv_add).enable(countdown != TIME_MINUTE_MAX);
            } catch (NumberFormatException e) {
                e.printStackTrace();
                etCountDown.setText(String.valueOf(TIME_MINUTE_MIN));
                a$.id(R.id.iv_sub).enable(false);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            // do nothing
        }
    };
    private ClickListener clickListener;

    class ClickListener implements View.OnClickListener {
        private int index;
        private ImageView imageView;

        public ClickListener(int index, ImageView imageView) {
            this.index = index;
            this.imageView = imageView;
        }

        @Override
        public void onClick(View v) {
            boolean isChecked = checkList.get(index);
            isChecked = !isChecked;
            checkList.set(index, isChecked);
            imageView.setVisibility(isChecked ? View.VISIBLE : View.INVISIBLE);
            checkOptionsSettingAnswer();
        }

    }

    private void checkOptionsSettingAnswer() {
        int size = checkList.size();
        int emptySize = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            boolean isChecked = checkList.get(i);
            if (isChecked) {
                hasSetRightAnswer = true;
                sb.append((char) ('A' + i));
                sb.append(" ");
            } else {
                emptySize++;
            }
        }
        hasSetRightAnswer = size != emptySize;
        TextView tvPublish = a$.id(R.id.tv_publish).view();
        if (hasSetRightAnswer) {
            String text = context.getString(R.string.base_timer_setted_answer, sb.toString());
            SpannableStringBuilder builder = new SpannableStringBuilder(text);
            ForegroundColorSpan whiteSpan = new ForegroundColorSpan(ThemeDataUtil.getColorFromThemeConfigByAttrId(
                    context, R.attr.base_theme_window_assistant_text_color));
            int index = text.indexOf("：");
            if (index != -1) {
                builder.setSpan(whiteSpan, index + 1, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            aa$.id(R.id.tv_setting_answer).text(builder);
            tvPublish.setSelected(true);
        } else {
            aa$.id(R.id.tv_setting_answer).text(getString(R.string.base_timer_setting_answer));
            tvPublish.setSelected(false);
        }
    }

    private boolean clearEditTextFocus(View view, MotionEvent event) {
        int leftTop[] = {0, 0};
        view.getLocationInWindow(leftTop);
        int left = leftTop[0];
        int top = leftTop[1];
        int bottom = top + view.getHeight();
        int right = left + view.getWidth();
        return !(event.getX() > left && event.getX() < right
                && event.getY() > top && event.getY() < bottom);
    }

    @Override
    protected boolean onTouchEvent(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN && isCustomEdit) {
            EditText etOptionRight = ab$.id(R.id.et_option_right).view();
            EditText etOptionWrong = ab$.id(R.id.et_option_wrong).view();
            if (clearEditTextFocus(etOptionRight, event) && clearEditTextFocus(etOptionWrong, event) &&
                    !TextUtils.isEmpty(etOptionRight.getText()) && !TextUtils.isEmpty(etOptionWrong.getText())) {
                etOptionRight.clearFocus();
                etOptionWrong.clearFocus();
            }
        }
        return super.onTouchEvent(v, event);
    }

    @Override
    protected View onCreateView(Context context) {
        setNeedShowShadow(true);
        final View view = View.inflate(context, R.layout.uibase_answerer_window, null);
        allowTouch = false;
        view.setBackground(ThemeDataUtil.getCommonWindowBg(context));
        return view;
    }

    @Override
    public void onDestroy() {
        LPRxUtils.dispose(disposables);
        LPRxUtils.dispose(timeDisposable);
        etRemark.removeTextChangedListener(remarkWatcher);
        etCountDown.removeTextChangedListener(countDownWatcher);
        super.onDestroy();
    }
}
